var jfRedirectByUserAgent = (function() {
  var userAgent = navigator.userAgent 
  var that = {
    cookieName: 'jfRedirectByUserAgent',
    
    doConditionalRedirect: function(url, userAgentWhitelist, userAgentBlacklist, confirmMessage) {
      if (userAgent) {

        for(var i=0; i<userAgentBlacklist.length; i++) {
          var regex = new RegExp(userAgentBlacklist[i], "i");
          if (regex.exec(userAgent)) {
            return false;
          }
        }

        for(var i=0; i<userAgentWhitelist.length; i++) {
          var regex = new RegExp(userAgentWhitelist[i], "i");
          if (regex.exec(userAgent)) {
            if(confirmMessage) {
              var confirmed = that.readCookieConfirmed();
              if (confirmed === null) {
                confirmed = confirm(confirmMessage) ? 1 : 0;
                that.writeCookieConfirmed(confirmed);
              }
              else {
                confirmed = parseInt(confirmed);
              }
              
              if (!confirmed) {
                return false;
              }
            }
            window.stop();
            document.location.href=decodeURIComponent(url);
          }
        }
      }      
    },
    
    writeCookieConfirmed: function(value) {
      document.cookie = that.cookieName+"="+value+"; path=/";
    },

    readCookieConfirmed: function() {
      var nameEQ = that.cookieName + "=";
      var ca = document.cookie.split(';');
      for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    }
  }
  
  return that;
})();
